#include <unordered_map>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>

#define N 2
#define NUM 1024

using namespace std;

void writer(int wfd){
	string s = "hello,I am a child!";
	int numbp = 0;
	pid_t self = getpid();

	char buffer[NUM];
	int cnt = 10;
	while(1){
		buffer[0] = 0;
		snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),self,numbp++);
		// cout << buffer << endl;
		write(wfd,buffer,strlen(buffer));
		// char c = 'c';
		// write(wfd,&c,1);
		cout << numbp << endl;
		sleep(1);
		//if(numbp >= 5) break;
	}
}

void reader(int rfd){
	char buffer[NUM];
	int time = 0;
	while(1){
		buffer[0] = '\0';
		int n = read(rfd,buffer,sizeof(buffer));
		if(n > 0){
			buffer[n] = '\0';
			cout << "father get msgs[" << getpid() << "]:" << buffer << endl;
		} 
		time++;
		sleep(1);
		cout << "n: " << n << endl;
		if(time >= 5) break;
	}
}

int main()
{
	int pipefd[N] = {0};
	int ret = pipe(pipefd);	
	if(ret < 0) return 1;

	// cout << "pipefd[0]:" << pipefd[0] << endl;
	// cout << "pipefd[1]:" << pipefd[1] << endl;

	pid_t id = fork();
	if(id < 0) return 2;
	if(id == 0){
		close(pipefd[0]);

		writer(pipefd[1]);
		
		close(pipefd[1]);
		exit(0);
	}
	else{
		close(pipefd[1]);

		reader(pipefd[0]);

		close(pipefd[0]);
		
		int status = 0;
		pid_t ret = waitpid(id,&status,0);//waitpid(id,&status,WNOHANG)进程返回的值为0，说明要再等等，小于0，说明没有等到，等待失败，大于0，说明成功等到，然后判断status带回的返回值是否有异常
		if(ret < 0) return 3;
		else{
			cout << "成功等到子进程" << endl;
			cout << "exit code:" << (status >> 8 & 0xff) << " exit sight:" << (status & 0x7f) << endl; 
		}

		//close(pipefd[0]);
	}

	return 0;
}
